package com.suxii.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.suxii.Thread.NettyThread;
import com.suxii.netty_demo.R;
import com.suxii.utils.Global;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class MyNettyService extends Service{

    public static String host;
    public static Integer port;

    public MyNettyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        Log.i("aa","onCreate");
        if (NettyThread.channel==null) {
            Log.e("aa","开启了新线程连接");
            host=getString(R.string.host);
            port= getResources().getInteger(R.integer.port);
            NettyThread nettyThread = new NettyThread();
            nettyThread.start();

            // TODO 传入服务上下文，临时解决方案
            Global.setContext(getApplicationContext());
            // TODO 传入uid，临时解决方案
            File file = new File(getApplicationContext().getFilesDir(), "info.sx");
                String[] s;
                try (var fis = new FileInputStream(file);
                     var br = new BufferedReader(new InputStreamReader(fis))) {
                    String line = br.readLine();
                    s = line.split("#");
                    Global.setUid(Integer.valueOf(s[0]));
                } catch (Exception e) {
                    e.printStackTrace();
                }

        }
    }


    @Override
    public void onDestroy() {
        Log.i("aa","onDestroy");
        if (NettyThread.channel!=null) {
            NettyThread.channel.close();
            NettyThread.channel=null;
        }
    }

}